<template>
  <div class="drugs-container">
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="药品名称">
          <el-input v-model="searchForm.name" placeholder="请输入药品名称" />
        </el-form-item>
        <el-form-item label="药品分类">
          <el-select v-model="searchForm.category" placeholder="请选择药品分类">
            <el-option label="全部" value="" />
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button type="success" @click="handleAdd">添加药品</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table :data="drugs" style="width: 100%">
      <el-table-column prop="name" label="药品名称" />
      <el-table-column prop="category" label="分类" />
      <el-table-column prop="specification" label="规格" />
      <el-table-column prop="manufacturer" label="厂家" />
      <el-table-column prop="price" label="价格">
        <template #default="{ row }">
          ¥{{ row.price.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="stock" label="库存" />
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑药品对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form :model="drugForm" :rules="rules" ref="drugFormRef" label-width="100px">
        <el-form-item label="药品名称" prop="name">
          <el-input v-model="drugForm.name" />
        </el-form-item>
        <el-form-item label="药品分类" prop="category">
          <el-select v-model="drugForm.category" style="width: 100%">
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="规格" prop="specification">
          <el-input v-model="drugForm.specification" />
        </el-form-item>
        <el-form-item label="厂家" prop="manufacturer">
          <el-input v-model="drugForm.manufacturer" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="drugForm.price" :precision="2" :step="0.1" :min="0" />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number v-model="drugForm.stock" :min="0" />
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleImageSuccess"
          >
            <img v-if="drugForm.image" :src="drugForm.image" class="drug-image">
            <el-button v-else>点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>

import { ref, reactive, onMounted } from 'vue'
import { getDrugs, getCategories, createDrug, updateDrug, deleteDrug } from '../../api'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'Drugs',
  setup() {
    const drugs = ref([])
    const categories = ref([])
    const searchForm = reactive({
      name: '',
      category: ''
    })
    const dialogVisible = ref(false)
    const dialogTitle = ref('')
    const drugFormRef = ref(null)
    const drugForm = reactive({
      name: '',
      category: '',
      specification: '',
      manufacturer: '',
      price: 0,
      stock: 0,
      image: ''
    })

    const rules = {
      name: [{ required: true, message: '请输入药品名称', trigger: 'blur' }],
      category: [{ required: true, message: '请选择药品分类', trigger: 'change' }],
      specification: [{ required: true, message: '请输入规格', trigger: 'blur' }],
      manufacturer: [{ required: true, message: '请输入厂家', trigger: 'blur' }],
      price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
      stock: [{ required: true, message: '请输入库存', trigger: 'blur' }]
    }

    const loadDrugs = async () => {
      try {
        const { data } = await getDrugs(searchForm)
        drugs.value = data
      } catch (error) {
        ElMessage.error('获取药品列表失败')
      }
    }

    const loadCategories = async () => {
      try {
        const { data } = await getCategories()
        categories.value = data
      } catch (error) {
        ElMessage.error('获取分类列表失败')
      }
    }

    const handleSearch = () => {
      loadDrugs()
    }

    const handleAdd = () => {
      dialogTitle.value = '添加药品'
      Object.assign(drugForm, {
        name: '',
        category: '',
        specification: '',
        manufacturer: '',
        price: 0,
        stock: 0,
        image: ''
      })
      dialogVisible.value = true
    }

    const handleEdit = (row) => {
      dialogTitle.value = '编辑药品'
      Object.assign(drugForm, row)
      dialogVisible.value = true
    }

    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm('确定要删除这个药品吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await deleteDrug(row.id)
        ElMessage.success('删除成功')
        loadDrugs()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    const handleSave = async () => {
      try {
        await drugFormRef.value.validate()
        if (drugForm.id) {
          await updateDrug(drugForm.id, drugForm)
        } else {
          await createDrug(drugForm)
        }
        dialogVisible.value = false
        ElMessage.success(drugForm.id ? '更新成功' : '添加成功')
        loadDrugs()
      } catch (error) {
        ElMessage.error(drugForm.id ? '更新失败' : '添加失败')
      }
    }

    const handleImageSuccess = (response) => {
      drugForm.image = response.url
    }

    onMounted(() => {
      loadDrugs()
      loadCategories()
    })

    return {
      drugs,
      categories,
      searchForm,
      dialogVisible,
      dialogTitle,
      drugForm,
      drugFormRef,
      rules,
      handleSearch,
      handleAdd,
      handleEdit,
      handleDelete,
      handleSave,
      handleImageSuccess
    }
  }
}
</script>

<style scoped>
.drugs-container {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  background: white;
  padding: 20px;
  border-radius: 4px;
}

.drug-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 